home *** CD-ROM | disk | FTP | other *** search
/ CD ROM Paradise Collection 4 / CD ROM Paradise Collection 4 1995 Nov.iso / clang / gnumake.zip / JOB.C < prev    next >
C/C++ Source or Header  |  1994-06-07  |  47KB  |  1,812 lines

  1. /* Job execution and handling for GNU Make.
  2. Copyright (C) 1988, 89, 90, 91, 92, 93, 94 Free Software Foundation, Inc.
  3. This file is part of GNU Make.
  4.  
  5. GNU Make is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9.  
  10. GNU Make is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. GNU General Public License for more details.
  14.  
  15. You should have received a copy of the GNU General Public License
  16. along with GNU Make; see the file COPYING.  If not, write to
  17. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  18.  
  19. #include "make.h"
  20. #include "commands.h"
  21. #include "job.h"
  22. #include "file.h"
  23. #include "variable.h"
  24. #ifdef __EMX__
  25. #include <process.h>
  26. #endif
  27. #ifdef HAVE_FCNTL_H
  28. #include <fcntl.h>
  29. #endif
  30.  
  31. #ifndef __EMX__
  32. /* Default path to search for executables.  */
  33. static char default_path[] = ":/bin:/usr/bin";
  34. /* Default shell to use.  */
  35. char default_shell[] = "/bin/sh";
  36. #else
  37. /* I don't know what would pass for reasonable under OS/2 */
  38. static char default_path[] = "\\os2;\\bin;\\usr\\bin";
  39. char default_shell[] = "\\os2\\cmd.exe";
  40. #endif
  41.  
  42. /* If NGROUPS_MAX == 0 then try other methods for finding a real value.  */
  43. #if defined (NGROUPS_MAX) && NGROUPS_MAX == 0
  44. #undef NGROUPS_MAX
  45. #endif /* NGROUPS_MAX == 0 */
  46.  
  47. #ifndef    NGROUPS_MAX
  48. #ifdef    POSIX
  49. #define    GET_NGROUPS_MAX    sysconf (_SC_NGROUPS_MAX)
  50. #else    /* Not POSIX.  */
  51. #define    NGROUPS_MAX    NGROUPS
  52. #endif    /* POSIX.  */
  53. #endif
  54.  
  55. #ifdef    HAVE_SYS_WAIT_H
  56. #include <sys/wait.h>
  57. #endif
  58.  
  59. #ifdef    HAVE_WAITPID
  60. #define    WAIT_NOHANG(status)    waitpid (-1, (status), WNOHANG)
  61. #else    /* Don't have waitpid.  */
  62. #ifdef    HAVE_WAIT3
  63. #ifndef    wait3
  64. extern int wait3 ();
  65. #endif
  66. #define    WAIT_NOHANG(status)    wait3 ((status), WNOHANG, (struct rusage *) 0)
  67. #endif    /* Have wait3.  */
  68. #endif    /* Have waitpid.  */
  69.  
  70. #if    !defined (wait) && !defined (POSIX)
  71. extern int wait ();
  72. #endif
  73.  
  74. #ifndef    HAVE_UNION_WAIT
  75.  
  76. #define    WAIT_T int
  77.  
  78. #ifndef    WTERMSIG
  79. #define WTERMSIG(x) ((x) & 0x7f)
  80. #endif
  81. #ifndef    WCOREDUMP
  82. #define WCOREDUMP(x) ((x) & 0x80)
  83. #endif
  84. #ifndef    WEXITSTATUS
  85. #define WEXITSTATUS(x) (((x) >> 8) & 0xff)
  86. #endif
  87. #ifndef    WIFSIGNALED
  88. #define WIFSIGNALED(x) (WTERMSIG (x) != 0)
  89. #endif
  90. #ifndef    WIFEXITED
  91. #define WIFEXITED(x) (WTERMSIG (x) == 0)
  92. #endif
  93.  
  94. #else    /* Have `union wait'.  */
  95.  
  96. #define WAIT_T union wait
  97. #ifndef    WTERMSIG
  98. #define WTERMSIG(x)    ((x).w_termsig)
  99. #endif
  100. #ifndef    WCOREDUMP
  101. #define WCOREDUMP(x)    ((x).w_coredump)
  102. #endif
  103. #ifndef WEXITSTATUS
  104. #define WEXITSTATUS(x)    ((x).w_retcode)
  105. #endif
  106. #ifndef    WIFSIGNALED
  107. #define    WIFSIGNALED(x)    (WTERMSIG(x) != 0)
  108. #endif
  109. #ifndef    WIFEXITED
  110. #define    WIFEXITED(x)    (WTERMSIG(x) == 0)
  111. #endif
  112.  
  113. #endif    /* Don't have `union wait'.  */
  114.  
  115.  
  116. #ifndef    HAVE_UNISTD_H
  117. extern int dup2 ();
  118. extern int execve ();
  119. extern void _exit ();
  120. extern int geteuid (), getegid ();
  121. extern int setgid (), getgid ();
  122. #endif
  123.  
  124. #ifndef    getdtablesize
  125. #ifdef HAVE_GETDTABLESIZE
  126. extern int getdtablesize ();
  127. #else
  128. #include <sys/param.h>
  129. #define getdtablesize() NOFILE
  130. #if !defined (NOFILE) && defined (NOFILES_MAX)
  131. /* SCO 3.2 "devsys 4.2" defines NOFILES_{MIN,MAX} in lieu of NOFILE.  */
  132. #define NOFILE    NOFILES_MAX
  133. #endif
  134. #endif
  135. #endif
  136.  
  137. extern int getloadavg ();
  138. extern int start_remote_job_p ();
  139. extern int start_remote_job (), remote_status ();
  140.  
  141. RETSIGTYPE child_handler ();
  142. static void free_child (), start_job_command ();
  143. static int load_too_high (), job_next_command ();
  144.  
  145. /* Chain of all live (or recently deceased) children.  */
  146.  
  147. struct child *children = 0;
  148.  
  149. /* Number of children currently running.  */
  150.  
  151. unsigned int job_slots_used = 0;
  152.  
  153. /* Nonzero if the `good' standard input is in use.  */
  154.  
  155. static int good_stdin_used = 0;
  156.  
  157. /* Chain of children waiting to run until the load average goes down.  */
  158.  
  159. static struct child *waiting_jobs = 0;
  160.  
  161. /* Write an error message describing the exit status given in
  162.    EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
  163.    Append "(ignored)" if IGNORED is nonzero.  */
  164.  
  165. static void
  166. child_error (target_name, exit_code, exit_sig, coredump, ignored)
  167.      char *target_name;
  168.      int exit_code, exit_sig, coredump;
  169.      int ignored;
  170. {
  171.   if (exit_sig == 0)
  172.     error (ignored ? "[%s] Error %d (ignored)" :
  173.        "*** [%s] Error %d",
  174.        target_name, exit_code);
  175.   else
  176.     {
  177.       char *coredump_string = coredump ? " (core dumped)" : "";
  178.       if (exit_sig > 0 && exit_sig < NSIG)
  179.     error ("*** [%s] %s%s",
  180.            target_name, sys_siglist[exit_sig], coredump_string);
  181.       else
  182.     error ("*** [%s] Signal %d%s", target_name, exit_sig, coredump_string);
  183.     }
  184. }
  185.  
  186. static unsigned int dead_children = 0;
  187.  
  188. /* Notice that a child died.
  189.    reap_children should be called when convenient.  */
  190. RETSIGTYPE
  191. child_handler (sig)
  192.      int sig;
  193. {
  194.   ++dead_children;
  195.  
  196.   if (debug_flag)
  197.     printf ("Got a SIGCHLD; %d unreaped children.\n", dead_children);
  198. }
  199.  
  200. extern int shell_function_pid, shell_function_completed;
  201.  
  202. /* Reap dead children, storing the returned status and the new command
  203.    state (`cs_finished') in the `file' member of the `struct child' for the
  204.    dead child, and removing the child from the chain.  If BLOCK nonzero,
  205.    reap at least one child, waiting for it to die if necessary.  If ERR is
  206.    nonzero, print an error message first.  */
  207.  
  208. void
  209. reap_children (block, err)
  210.      int block, err;
  211. {
  212.   WAIT_T status;
  213.  
  214.   while ((children != 0 || shell_function_pid != 0) &&
  215.      (block || dead_children > 0))
  216.     {
  217.       int remote = 0;
  218.       register int pid;
  219.       int exit_code, exit_sig, coredump;
  220.       register struct child *lastc, *c;
  221.       int child_failed;
  222.       int any_remote, any_local;
  223.  
  224.       if (err && dead_children == 0)
  225.     {
  226.       /* We might block for a while, so let the user know why.  */
  227.       fflush (stdout);
  228.       error ("*** Waiting for unfinished jobs....");
  229.     }
  230.  
  231.       /* We have one less dead child to reap.
  232.      The test and decrement are not atomic; if it is compiled into:
  233.          register = dead_children - 1;
  234.         dead_children = register;
  235.      a SIGCHLD could come between the two instructions.
  236.      child_handler increments dead_children.
  237.      The second instruction here would lose that increment.  But the
  238.      only effect of dead_children being wrong is that we might wait
  239.      longer than necessary to reap a child, and lose some parallelism;
  240.      and we might print the "Waiting for unfinished jobs" message above
  241.      when not necessary.  */
  242.  
  243.       if (dead_children != 0)
  244.     --dead_children;
  245.  
  246.       any_remote = 0;
  247.       any_local = shell_function_pid != -1;
  248.       for (c = children; c != 0; c = c->next)
  249.     {
  250.       any_remote |= c->remote;
  251.       any_local |= ! c->remote;
  252.       if (debug_flag)
  253.         printf ("Live child 0x%08lx PID %d%s\n",
  254.             (unsigned long int) c,
  255.             c->pid, c->remote ? " (remote)" : "");
  256.     }
  257.  
  258.       /* First, check for remote children.  */
  259.       if (any_remote)
  260.     pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
  261.       else
  262.     pid = 0;
  263.       if (pid < 0)
  264.     {
  265.     remote_status_lose:
  266. #ifdef    EINTR
  267.       if (errno == EINTR)
  268.         continue;
  269. #endif
  270.       pfatal_with_name ("remote_status");
  271.     }
  272.       else if (pid == 0)
  273.     {
  274.       /* No remote children.  Check for local children.  */
  275.  
  276.       if (any_local)
  277.         {
  278. #ifdef    WAIT_NOHANG
  279.           if (!block)
  280.         pid = WAIT_NOHANG (&status);
  281.           else
  282. #endif
  283.         pid = wait (&status);
  284.         }
  285.       else
  286.         pid = 0;
  287.  
  288.       if (pid < 0)
  289.         {
  290. #ifdef    EINTR
  291.           if (errno == EINTR)
  292.         continue;
  293. #endif
  294.           pfatal_with_name ("wait");
  295.         }
  296.       else if (pid == 0)
  297.         {
  298.           /* No local children.  */
  299.           if (block && any_remote)
  300.         {
  301.           /* Now try a blocking wait for a remote child.  */
  302.           pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
  303.           if (pid < 0)
  304.             goto remote_status_lose;
  305.           else if (pid == 0)
  306.             /* No remote children either.  Finally give up.  */
  307.             break;
  308.           else
  309.             /* We got a remote child.  */
  310.             remote = 1;
  311.         }
  312.           else
  313.         break;
  314.         }
  315.       else
  316.         {
  317.           /* Chop the status word up.  */
  318.           exit_code = WEXITSTATUS (status);
  319.           exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
  320.           coredump = WCOREDUMP (status);
  321.         }
  322.     }
  323.       else
  324.     /* We got a remote child.  */
  325.     remote = 1;
  326.  
  327.       /* Check if this is the child of the `shell' function.  */
  328.       if (!remote && pid == shell_function_pid)
  329.     {
  330.       /* It is.  Leave an indicator for the `shell' function.  */
  331.       if (exit_sig == 0 && exit_code == 127)
  332.         shell_function_completed = -1;
  333.       else
  334.         shell_function_completed = 1;
  335.       break;
  336.     }
  337.  
  338.       child_failed = exit_sig != 0 || exit_code != 0;
  339.  
  340.       /* Search for a child matching the deceased one.  */
  341.       lastc = 0;
  342.       for (c = children; c != 0; lastc = c, c = c->next)
  343.     if (c->remote == remote && c->pid == pid)
  344.       break;
  345.  
  346.       if (c == 0)
  347.     {
  348.       /* An unknown child died.  */
  349.       char buf[100];
  350.       sprintf (buf, "Unknown%s job %d", remote ? " remote" : "", pid);
  351.       if (child_failed)
  352.         child_error (buf, exit_code, exit_sig, coredump,
  353.              ignore_errors_flag);
  354.       else
  355.         error ("%s finished.", buf);
  356.     }
  357.       else
  358.     {
  359.       if (debug_flag)
  360.         printf ("Reaping %s child 0x%08lx PID %d%s\n",
  361.             child_failed ? "losing" : "winning",
  362.             (unsigned long int) c,
  363.             c->pid, c->remote ? " (remote)" : "");
  364.  
  365.       /* If this child had the good stdin, say it is now free.  */
  366.       if (c->good_stdin)
  367.         good_stdin_used = 0;
  368.  
  369.       if (child_failed && !c->noerror && !ignore_errors_flag)
  370.         {
  371.           /* The commands failed.  Write an error message,
  372.          delete non-precious targets, and abort.  */
  373.           child_error (c->file->name, exit_code, exit_sig, coredump, 0);
  374.           c->file->update_status = 1;
  375.           if (exit_sig != 0)
  376.         delete_child_targets (c);
  377.         }
  378.       else
  379.         {
  380.           if (child_failed)
  381.         {
  382.           /* The commands failed, but we don't care.  */
  383.           child_error (c->file->name,
  384.                    exit_code, exit_sig, coredump, 1);
  385.           child_failed = 0;
  386.         }
  387.  
  388.           /* If there are more commands to run, try to start them.  */
  389.           if (job_next_command (c))
  390.         {
  391.           if (handling_fatal_signal)
  392.             {
  393.               /* Never start new commands while we are dying.
  394.              Since there are more commands that wanted to be run,
  395.              the target was not completely remade.  So we treat
  396.              this as if a command had failed.  */
  397.               c->file->command_state = cs_finished;
  398.               c->file->update_status = 1;
  399.             }
  400.           else
  401.             {
  402.               /* Check again whether to start remotely.
  403.              Whether or not we want to changes over time.
  404.              Also, start_remote_job may need state set up
  405.              by start_remote_job_p.  */
  406.               c->remote = start_remote_job_p ();
  407.               start_job_command (c);
  408.             }
  409.         }
  410.  
  411.           switch (c->file->command_state)
  412.         {
  413.         case cs_running:
  414.           /* Successfully started.  Loop to reap more children.  */
  415.           continue;
  416.  
  417.         case cs_finished:
  418.           if (c->file->update_status != 0)
  419.             /* We failed to start the commands.  */
  420.             delete_child_targets (c);
  421.           break;
  422.  
  423.         default:
  424.           error ("internal error: `%s' has bogus command_state \
  425. %d in reap_children",
  426.              c->file->name, (int) c->file->command_state);
  427.           abort ();
  428.           break;
  429.         }
  430.         }
  431.  
  432.       if (! handling_fatal_signal)
  433.         /* Notice if the target of the commands has been changed.  */
  434.         notice_finished_file (c->file);
  435.  
  436.       if (debug_flag)
  437.         printf ("Removing child 0x%08lx PID %d%s from chain.\n",
  438.             (unsigned long int) c,
  439.             c->pid, c->remote ? " (remote)" : "");
  440.  
  441.       /* Remove the child from the chain and free it.  */
  442.       if (lastc == 0)
  443.         children = c->next;
  444.       else
  445.         lastc->next = c->next;
  446.       if (! handling_fatal_signal) /* Avoid nonreentrancy.  */
  447.         free_child (c);
  448.  
  449.       /* There is now another slot open.  */
  450.       --job_slots_used;
  451.  
  452.       /* If the job failed, and the -k flag was not given, die,
  453.          unless we are already in the process of dying.  */
  454.       if (!err && child_failed && !keep_going_flag)
  455.         die (2);
  456.     }
  457.  
  458.       /* Only block for one child.  */
  459.       block = 0;
  460.     }
  461. }
  462.  
  463. /* Free the storage allocated for CHILD.  */
  464.  
  465. static void
  466. free_child (child)
  467.      register struct child *child;
  468. {
  469.   if (child->command_lines != 0)
  470.     {
  471.       register unsigned int i;
  472.       for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
  473.     free (child->command_lines[i]);
  474.       free ((char *) child->command_lines);
  475.     }
  476.  
  477.   if (child->environment != 0)
  478.     {
  479.       register char **ep = child->environment;
  480.       while (*ep != 0)
  481.     free (*ep++);
  482.       free ((char *) child->environment);
  483.     }
  484.  
  485.   free ((char *) child);
  486. }
  487.  
  488. #ifdef    POSIX
  489. extern sigset_t fatal_signal_set;
  490.  
  491. void
  492. unblock_sigs ()
  493. {
  494.   sigset_t empty;
  495.   sigemptyset (&empty);
  496.   sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
  497. }
  498. #endif
  499.  
  500. /* Start a job to run the commands specified in CHILD.
  501.    CHILD is updated to reflect the commands and ID of the child process.  */
  502.  
  503. static void
  504. start_job_command (child)
  505.      register struct child *child;
  506. {
  507.   static int bad_stdin = -1;
  508.   register char *p;
  509.   int flags = child->file->cmds->lines_flags[child->command_line - 1];
  510.   char **argv;
  511.  
  512.   p = child->command_ptr;
  513.   child->noerror = flags & COMMANDS_NOERROR;
  514.   while (*p != '\0')
  515.     {
  516.       if (*p == '@')
  517.     flags |= COMMANDS_SILENT;
  518.       else if (*p == '+')
  519.     flags |= COMMANDS_RECURSE;
  520.       else if (*p == '-')
  521.     child->noerror = 1;
  522.       else if (!isblank (*p) && *p != '+')
  523.     break;
  524.       ++p;
  525.     }
  526.  
  527.   /* If -q was given, just say that updating `failed'.  The exit status of
  528.      1 tells the user that -q is saying `something to do'; the exit status
  529.      for a random error is 2.  */
  530.   if (question_flag && !(flags & COMMANDS_RECURSE))
  531.     {  
  532.       child->file->update_status = 1;
  533.       child->file->command_state = cs_finished;
  534.       return;
  535.     }
  536.  
  537.   /* There may be some preceding whitespace left if there
  538.      was nothing but a backslash on the first line.  */
  539.   p = next_token (p);
  540.   
  541.   /* Figure out an argument list from this command line.  */
  542.   
  543.   {
  544.     char *end;
  545.     argv = construct_command_argv (p, &end, child->file);
  546.     if (end == NULL)
  547.       child->command_ptr = NULL;
  548.     else
  549.       {
  550.     *end++ = '\0';
  551.     child->command_ptr = end;
  552.       }
  553.   }
  554.  
  555.   if (touch_flag && !(flags & COMMANDS_RECURSE))
  556.     {
  557.       /* Go on to the next command.  It might be the recursive one.
  558.      We construct ARGV only to find the end of the command line.  */
  559.       free (argv[0]);
  560.       free ((char *) argv);
  561.       argv = 0;
  562.     }
  563.  
  564.   if (argv == 0)
  565.     {
  566.       /* This line has no commands.  Go to the next.  */
  567.       if (job_next_command (child))
  568.     start_job_command (child);
  569.       return;
  570.     }
  571.  
  572.   /* Print out the command.  */
  573.  
  574.   if (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
  575.     puts (p);
  576.  
  577.   /* Tell update_goal_chain that a command has been started on behalf of
  578.      this target.  It is important that this happens here and not in
  579.      reap_children (where we used to do it), because reap_children might be
  580.      reaping children from a different target.  We want this increment to
  581.      guaranteedly indicate that a command was started for the dependency
  582.      chain (i.e., update_file recursion chain) we are processing.  */
  583.  
  584.   ++commands_started;
  585.  
  586.   /* If -n was given, recurse to get the next line in the sequence.  */
  587.  
  588.   if (just_print_flag && !(flags & COMMANDS_RECURSE))
  589.     {
  590.       free (argv[0]);
  591.       free ((char *) argv);
  592.       if (job_next_command (child))
  593.     start_job_command (child);
  594.       return;
  595.     }
  596.  
  597.   /* Flush the output streams so they won't have things written twice.  */
  598.  
  599.   fflush (stdout);
  600.   fflush (stderr);
  601.   
  602.   /* Set up a bad standard input that reads from a broken pipe.  */
  603.  
  604.   if (bad_stdin == -1)
  605.     {
  606.       /* Make a file descriptor that is the read end of a broken pipe.
  607.      This will be used for some children's standard inputs.  */
  608.       int pd[2];
  609.       if (pipe (pd) == 0)
  610.     {
  611.       /* Close the write side.  */
  612.       (void) close (pd[1]);
  613.       /* Save the read side.  */
  614.       bad_stdin = pd[0];
  615.     }
  616.     }
  617.  
  618.   /* Decide whether to give this child the `good' standard input
  619.      (one that points to the terminal or whatever), or the `bad' one
  620.      that points to the read side of a broken pipe.  */
  621.  
  622.   child->good_stdin = !good_stdin_used;
  623.   if (child->good_stdin)
  624.     good_stdin_used = 1;
  625.  
  626.   child->deleted = 0;
  627.  
  628.   /* Set up the environment for the child.  */
  629.   if (child->environment == 0)
  630.     child->environment = target_environment (child->file);
  631.  
  632.   /* start_waiting_job has set CHILD->remote if we can start a remote job.  */
  633.   if (child->remote)
  634.     {
  635.       int is_remote, id, used_stdin;
  636.       if (start_remote_job (argv, child->environment,
  637.                 child->good_stdin ? 0 : bad_stdin,
  638.                 &is_remote, &id, &used_stdin))
  639.     goto error;
  640.       else
  641.     {
  642.       if (child->good_stdin && !used_stdin)
  643.         {
  644.           child->good_stdin = 0;
  645.           good_stdin_used = 0;
  646.         }
  647.       child->remote = is_remote;
  648.       child->pid = id;
  649.     }
  650.     }
  651.   else
  652.     {
  653.       /* Fork the child process.  */
  654.  
  655. #ifdef     POSIX
  656.       (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
  657. #else
  658. #ifdef    HAVE_SIGSETMASK
  659.       (void) sigblock (fatal_signal_mask);
  660. #endif
  661. #endif
  662.  
  663.       child->remote = 0;
  664. #ifndef __EMX__
  665.       child->pid = vfork ();
  666.       if (child->pid == 0)
  667.     {
  668.       /* We are the child side.  */
  669.       unblock_sigs ();
  670.       child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
  671.                  argv, child->environment);
  672.     }
  673.       else if (child->pid < 0)
  674.     {
  675.       /* Fork failed!  */
  676.       unblock_sigs ();
  677.       perror_with_name ("vfork", "");
  678.       goto error;
  679.     }
  680. #else
  681.       child->pid = child_execute_job(child->good_stdin ? 0 : bad_stdin, 1,
  682.                      argv, child->environment);
  683.       /* if we've opened a pipe for the stdin of this command,
  684.        * close it after the spawn, since we don't exec and let
  685.        * the child handles croak of their own free will.
  686.        */
  687.       if(!child->good_stdin)
  688.     close(bad_stdin);
  689.       if(child->pid < 0) {
  690.     unblock_sigs();
  691.     goto error;
  692.       }
  693. #endif
  694.     }
  695.  
  696.   /* We are the parent side.  Set the state to
  697.      say the commands are running and return.  */
  698.  
  699.   child->file->command_state = cs_running;
  700.  
  701.   /* Free the storage used by the child's argument list.  */
  702.  
  703.   free (argv[0]);
  704.   free ((char *) argv);
  705.  
  706.   return;
  707.  
  708.  error:
  709.   child->file->update_status = 2;
  710.   child->file->command_state = cs_finished;
  711. }
  712.  
  713. /* Try to start a child running.
  714.    Returns nonzero if the child was started (and maybe finished), or zero if
  715.    the load was too high and the child was put on the `waiting_jobs' chain.  */
  716.  
  717. static int
  718. start_waiting_job (c)
  719.      struct child *c;
  720. {
  721.   /* If we can start a job remotely, we always want to, and don't care about
  722.      the local load average.  We record that the job should be started
  723.      remotely in C->remote for start_job_command to test.  */
  724.  
  725.   c->remote = start_remote_job_p ();
  726.  
  727.   /* If this job is to be started locally, and we are already running
  728.      some jobs, make this one wait if the load average is too high.  */
  729.   if (!c->remote && job_slots_used > 0 && load_too_high ())
  730.     {
  731.       /* Put this child on the chain of children waiting
  732.      for the load average to go down.  */
  733.       c->file->command_state = cs_running;
  734.       c->next = waiting_jobs;
  735.       waiting_jobs = c;
  736.       return 0;
  737.     }
  738.  
  739.   /* Start the first command; reap_children will run later command lines.  */
  740.   start_job_command (c);
  741.  
  742.   switch (c->file->command_state)
  743.     {
  744.     case cs_running:
  745.       c->next = children;
  746.       if (debug_flag)
  747.     printf ("Putting child 0x%08lx PID %05d%s on the chain.\n",
  748.         (unsigned long int) c,
  749.         c->pid, c->remote ? " (remote)" : "");
  750.       children = c;
  751.       /* One more job slot is in use.  */
  752.       ++job_slots_used;
  753.       unblock_sigs ();
  754.       break;
  755.  
  756.     case cs_finished:
  757.       notice_finished_file (c->file);
  758.       free_child (c);
  759.       break;
  760.  
  761.     default:
  762.       error ("internal error: `%s' command_state == %d in new_job",
  763.          c->file->name, (int) c->file->command_state);
  764.       abort ();
  765.       break;
  766.     }
  767.  
  768.   return 1;
  769. }
  770.  
  771. /* Create a `struct child' for FILE and start its commands running.  */
  772.  
  773. void
  774. new_job (file)
  775.      register struct file *file;
  776. {
  777.   register struct commands *cmds = file->cmds;
  778.   register struct child *c;
  779.   char **lines;
  780.   register unsigned int i;
  781.  
  782.   /* Let any previously decided-upon jobs that are waiting
  783.      for the load to go down start before this new one.  */
  784.   start_waiting_jobs ();
  785.  
  786.   /* Reap any children that might have finished recently.  */
  787.   reap_children (0, 0);
  788.  
  789.   /* Chop the commands up into lines if they aren't already.  */
  790.   chop_commands (cmds);
  791.  
  792.   if (job_slots != 0)
  793.     /* Wait for a job slot to be freed up.  */
  794.     while (job_slots_used == job_slots)
  795.       reap_children (1, 0);
  796.  
  797.   /* Expand the command lines and store the results in LINES.  */
  798.   lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
  799.   for (i = 0; i < cmds->ncommand_lines; ++i)
  800.     {
  801.       /* Collapse backslash-newline combinations that are inside variable
  802.      or function references.  These are left alone by the parser so
  803.      that they will appear in the echoing of commands (where they look
  804.      nice); and collapsed by construct_command_argv when it tokenizes.
  805.      But letting them survive inside function invocations loses because
  806.      we don't want the functions to see them as part of the text.  */
  807.  
  808.       char *in, *out, *ref;
  809.  
  810.       /* IN points to where in the line we are scanning.
  811.      OUT points to where in the line we are writing.
  812.      When we collapse a backslash-newline combination,
  813.      IN gets ahead out OUT.  */
  814.  
  815.       in = out = cmds->command_lines[i];
  816.       while ((ref = index (in, '$')) != 0)
  817.     {
  818.       ++ref;        /* Move past the $.  */
  819.  
  820.       if (out != in)
  821.         /* Copy the text between the end of the last chunk
  822.            we processed (where IN points) and the new chunk
  823.            we are about to process (where REF points).  */
  824.         bcopy (in, out, ref - in);
  825.  
  826.       /* Move both pointers past the boring stuff.  */
  827.       out += ref - in;
  828.       in = ref;
  829.  
  830.       if (*ref == '(' || *ref == '{')
  831.         {
  832.           char openparen = *ref;
  833.           char closeparen = openparen == '(' ? ')' : '}';
  834.           int count;
  835.           char *p;
  836.  
  837.           *out++ = *in++;    /* Copy OPENPAREN.  */
  838.           /* IN now points past the opening paren or brace.
  839.          Count parens or braces until it is matched.  */
  840.           count = 0;
  841.           while (*in != '\0')
  842.         {
  843.           if (*in == closeparen && --count < 0)
  844.             break;
  845.           else if (*in == '\\' && in[1] == '\n')
  846.             {
  847.               /* We have found a backslash-newline inside a
  848.              variable or function reference.  Eat it and
  849.              any following whitespace.  */
  850.  
  851.               int quoted = 0;
  852.               for (p = in - 1; p > ref && *p == '\\'; --p)
  853.             quoted = !quoted;
  854.  
  855.               if (quoted)
  856.             /* There were two or more backslashes, so this is
  857.                not really a continuation line.  We don't collapse
  858.                the quoting backslashes here as is done in
  859.                collapse_continuations, because the line will
  860.                be collapsed again after expansion.  */
  861.             *out++ = *in++;
  862.               else
  863.             {
  864.               /* Skip the backslash, newline and
  865.                  any following whitespace.  */
  866.               in = next_token (in + 2);
  867.  
  868.               /* Discard any preceding whitespace that has
  869.                  already been written to the output.  */
  870.               while (out > ref && isblank (out[-1]))
  871.                 --out;
  872.  
  873.               /* Replace it all with a single space.  */
  874.               *out++ = ' ';
  875.             }
  876.             }
  877.           else
  878.             {
  879.               if (*in == openparen)
  880.             ++count;
  881.  
  882.               *out++ = *in++;
  883.             }
  884.         }
  885.         }
  886.     }
  887.  
  888.       /* There are no more references in this line to worry about.
  889.      Copy the remaining uninteresting text to the output.  */
  890.       if (out != in)
  891.     strcpy (out, in);
  892.  
  893.       /* Finally, expand the line.  */
  894.       lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
  895.                              file);
  896.     }
  897.  
  898.   /* Start the command sequence, record it in a new
  899.      `struct child', and add that to the chain.  */
  900.  
  901.   c = (struct child *) xmalloc (sizeof (struct child));
  902.   c->file = file;
  903.   c->command_lines = lines;
  904.   c->command_line = 0;
  905.   c->command_ptr = 0;
  906.   c->environment = 0;
  907.  
  908.   /* Fetch the first command line to be run.  */
  909.   if (! job_next_command (c))
  910.     /* There were no commands!  */
  911.     free_child (c);
  912.   else
  913.     {
  914.       /* The job is now primed.  Start it running.  */
  915.       start_waiting_job (c);
  916.  
  917.       if (job_slots == 1)
  918.     /* Since there is only one job slot, make things run linearly.
  919.        Wait for the child to die, setting the state to `cs_finished'.  */
  920.     while (file->command_state == cs_running)
  921.       reap_children (1, 0);
  922.     }
  923. }
  924.  
  925. /* Move CHILD's pointers to the next command for it to execute.
  926.    Returns nonzero if there is another command.  */
  927.  
  928. static int
  929. job_next_command (child)
  930.      struct child *child;
  931. {
  932.   if (child->command_ptr == 0 || *child->command_ptr == '\0')
  933.     {
  934.       /* There are no more lines in the expansion of this line.  */
  935.       if (child->command_line == child->file->cmds->ncommand_lines)
  936.     {
  937.       /* There are no more lines to be expanded.  */
  938.       child->command_ptr = 0;
  939.       child->file->command_state = cs_finished;
  940.       child->file->update_status = 0;
  941.       return 0;
  942.     }
  943.       else
  944.     /* Get the next line to run.  */
  945.     child->command_ptr = child->command_lines[child->command_line++];
  946.     }
  947.   return 1;
  948. }
  949.  
  950. static int
  951. load_too_high ()
  952. {
  953.   extern int getloadavg ();
  954.   double load;
  955.  
  956.   if (max_load_average < 0)
  957.     return 0;
  958.  
  959.   make_access ();
  960.   if (getloadavg (&load, 1) != 1)
  961.     {
  962.       static int lossage = -1;
  963.       /* Complain only once for the same error.  */
  964.       if (lossage == -1 || errno != lossage)
  965.     {
  966.       if (errno == 0)
  967.         /* An errno value of zero means getloadavg is just unsupported.  */
  968.         error ("cannot enforce load limits on this operating system");
  969.       else
  970.         perror_with_name ("cannot enforce load limit: ", "getloadavg");
  971.     }
  972.       lossage = errno;
  973.       load = 0;
  974.     }
  975.   user_access ();
  976.  
  977.   return load >= max_load_average;
  978. }
  979.  
  980. /* Start jobs that are waiting for the load to be lower.  */
  981.  
  982. void
  983. start_waiting_jobs ()
  984. {
  985.   struct child *job;
  986.  
  987.   if (waiting_jobs == 0)
  988.     return;
  989.  
  990.   do
  991.     {
  992.       /* Check for recently deceased descendants.  */
  993.       reap_children (0, 0);
  994.  
  995.       /* Take a job off the waiting list.  */
  996.       job = waiting_jobs;
  997.       waiting_jobs = job->next;
  998.  
  999.       /* Try to start that job.  We break out of the loop as soon
  1000.      as start_waiting_job puts one back on the waiting list.  */
  1001.     } while (start_waiting_job (job) && waiting_jobs != 0);
  1002. }
  1003.  
  1004. /* Replace the current process with one executing the command in ARGV.
  1005.    STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
  1006.    the environment of the new program.  This function does not return.  */
  1007.  
  1008. #ifndef __EMX__
  1009. void
  1010. #else
  1011. int
  1012. #endif
  1013. child_execute_job (stdin_fd, stdout_fd, argv, envp)
  1014.      int stdin_fd, stdout_fd;
  1015.      char **argv, **envp;
  1016. {
  1017. #ifdef __EMX__
  1018.   int oldstdin = dup(0), oldstdout = dup(1), rval;
  1019.   fcntl(oldstdin, F_SETFD, 1);
  1020.   fcntl(oldstdout, F_SETFD, 1);
  1021. #endif
  1022.   if (stdin_fd != 0)
  1023.     (void) dup2 (stdin_fd, 0);
  1024.   if (stdout_fd != 1)
  1025.     (void) dup2 (stdout_fd, 1);
  1026.  
  1027. #ifndef __EMX__
  1028.   /* Free up file descriptors.  */
  1029.   {
  1030.     register int d;
  1031.     int max = getdtablesize ();
  1032.     for (d = 3; d < max; ++d)
  1033.       (void) close (d);
  1034.   }
  1035.   /* Run the command.  */
  1036.   exec_command (argv, envp);
  1037. #else
  1038.   rval = exec_command (argv, envp);
  1039.   dup2(oldstdin,0); dup2(oldstdout,1);
  1040.   close(oldstdin); close(oldstdout);
  1041.   return rval;
  1042. #endif
  1043. }
  1044.  
  1045. /* Return one if the file is an internal SHELL command
  1046.    Return zero otherwise
  1047.  */
  1048. static int
  1049. is_shell_command(str)
  1050.      char *str;
  1051. {    
  1052.   register int j;
  1053. #ifndef __EMX__    
  1054.   static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
  1055.                              "logout", "set", "umask", "wait", "while", "for",
  1056.                              "case", "if", ":", ".", "break", "continue",
  1057.                              "export", "read", "readonly", "shift", "times",
  1058.                              "trap", "switch", 0 };
  1059.   for (j = 0; sh_cmds[j] != 0; ++j)
  1060.     if (streq (sh_cmds[j], str))
  1061.       return 1;
  1062. #else
  1063.   static char *sh_cmds[] = {
  1064.     "call","cd","chcp","chdir","cls","copy","date","del","detach",
  1065.     "dir","do","echo","else","endlocal","erase","errorlevel","exist",
  1066.     "exit","extproc","for","goto","if","in","keys","md","mkdir","move",
  1067.     "not","path","pause","prompt","rd","rem","ren","rename","rmdir",
  1068.     "set","setlocal","shift","start","time","type","ver","verify","vol",0
  1069.   };
  1070.   /* Shell command can be either upper or lower case */
  1071.   for (j = 0; sh_cmds[j] != 0; ++j)
  1072.     if(stricmp(sh_cmds[j], str) == 0)
  1073.       return 1;
  1074. #endif          
  1075.   return 0;
  1076. }
  1077.  
  1078.  
  1079. /* Search PATH for FILE.
  1080.    If successful, store the full pathname in PROGRAM and return 1.
  1081.    If not sucessful, return zero.  */
  1082.  
  1083. static int
  1084. search_path (file, path, program)
  1085.      char *file, *path, *program;
  1086. {
  1087.   if (path == 0 || path[0] == '\0')
  1088.     path = default_path;
  1089.  
  1090. #ifndef __EMX__
  1091.   if (index (file, '/') != 0)
  1092. #else
  1093.   if (index(file,'/') != 0 || index (file, '\\') != 0 || file[1] == ':')
  1094. #endif
  1095.     {
  1096.       strcpy (program, file);
  1097.       return 1;
  1098.     }
  1099.   else
  1100.     {
  1101.       unsigned int len;
  1102.  
  1103. #ifdef    HAVE_GETGROUPS
  1104. #ifndef    HAVE_UNISTD_H
  1105.       extern int getgroups ();
  1106. #endif
  1107.       static int ngroups = -1;
  1108. #ifdef    NGROUPS_MAX
  1109.       static GETGROUPS_T groups[NGROUPS_MAX];
  1110. #define    ngroups_max    NGROUPS_MAX
  1111. #else
  1112.       static GETGROUPS_T *groups = 0;
  1113.       static int ngroups_max;
  1114.       if (groups == 0)
  1115.     {
  1116.       ngroups_max = GET_NGROUPS_MAX;
  1117.       groups = (GETGROUPS_T *) malloc (ngroups_max * sizeof (GETGROUPS_T));
  1118.     }
  1119. #endif
  1120.       if (groups != 0 && ngroups == -1)
  1121.     ngroups = getgroups (ngroups_max, groups);
  1122. #endif    /* Have getgroups.  */
  1123.  
  1124.       len = strlen (file) + 1;
  1125. #ifdef __EMX__
  1126.       /* the standard OS/2 behavior is to look in CWD */
  1127.       {
  1128.     struct stat st;
  1129.     if(stat(file,&st) == 0) {
  1130.       strcpy(program,file);
  1131.       return 1;
  1132.     }
  1133.       }
  1134. #endif
  1135.       do
  1136.     {
  1137.       struct stat st;
  1138.       int perm;
  1139.       char *p;
  1140.  
  1141. #ifndef __EMX__
  1142.       p = index (path, ':');
  1143. #else
  1144.       p = index (path, ';');
  1145. #endif
  1146.       if (p == 0)
  1147.         p = path + strlen (path);
  1148.  
  1149.       if (p == path)
  1150.         bcopy (file, program, len);
  1151.       else
  1152.         {
  1153.           bcopy (path, program, p - path);
  1154.           program[p - path] = '/';
  1155.           bcopy (file, program + (p - path) + 1, len);
  1156.         }
  1157.  
  1158.       if (stat (program, &st) == 0
  1159.           && S_ISREG (st.st_mode))
  1160.         {
  1161.           if (st.st_uid == geteuid ())
  1162.         perm = (st.st_mode & 0100);
  1163.           else if (st.st_gid == getegid ())
  1164.         perm = (st.st_mode & 0010);
  1165.           else
  1166.         {
  1167. #ifdef    HAVE_GETGROUPS
  1168.           register int i;
  1169.           for (i = 0; i < ngroups; ++i)
  1170.             if (groups[i] == st.st_gid)
  1171.               break;
  1172.           if (i < ngroups)
  1173.             perm = (st.st_mode & 0010);
  1174.           else
  1175. #endif    /* Have getgroups.  */
  1176.             perm = (st.st_mode & 0001);
  1177.         }
  1178.  
  1179.           if (perm != 0)
  1180.         return 1;
  1181.         }
  1182.  
  1183.       path = p + 1;
  1184.     } while (*path != '\0');
  1185.     }
  1186.  
  1187.   return 0;
  1188. }
  1189.  
  1190. #ifdef __EMX__
  1191.  
  1192. /* Using something DOSISH all executables have extentions 
  1193. /* So append these and then search for them in the path.
  1194.  */
  1195. static int
  1196. emx_search_path (file, path, program)
  1197.      char *file, *path, *program;
  1198. {
  1199.   static char *suffixes[] = { ".exe", ".com", ".cmd", ".bat", NULL };
  1200.   char *dot, tmp[PATH_MAX]; 
  1201.   int i,namelen;
  1202.  
  1203.   if (search_path(file,path,program)==1)
  1204.     return 1;
  1205.  
  1206.   if ((namelen = strlen(file)) < 4 || file[namelen-4] != '.') {
  1207.     for (i = 0; suffixes[i]; i++) {
  1208.       strcpy(tmp,file);
  1209.       strcat(tmp,suffixes[i]);
  1210.       if (search_path(tmp,path,program) == 1) {
  1211.     return 1;
  1212.       }
  1213.     }
  1214.   }
  1215.  
  1216.   return 0;
  1217. }
  1218.  
  1219. /* Have people call emx_search_path in the remainder of the program.
  1220. /* This will mimic regular behaviour.
  1221.  */
  1222. #define search_path emx_search_path 
  1223.  
  1224. /* Return zero if the file is not a script.
  1225.    Return one if it is a script.
  1226.  */
  1227. static int
  1228. is_script(file)
  1229.     char *file;
  1230. {
  1231.     static char *script_suffixes[] = { ".cmd", ".bat", NULL };
  1232.     int i, namelen;
  1233.     char *tmp;
  1234.     struct stat st;
  1235.     PATH_VAR(prog);
  1236.     
  1237.     /* setup a temporary file name, which is lower case. */
  1238.     namelen = strlen(file);
  1239.     tmp = malloc(namelen+5);
  1240.     strcpy(tmp,file); 
  1241.     strlwr(tmp);
  1242.     for (i=0; script_suffixes[i]; i++) {
  1243.         /* does it contain the extension */
  1244.         if (strstr(file,script_suffixes[i])!=NULL) {
  1245.             /* the user thinks it should be a script */
  1246.             return 1;   
  1247.         } else {
  1248.             if (file[namelen-4] == '.') {
  1249.                 /* it did have an extension so it can't be a script */
  1250.                 return 0;
  1251.             }  else {
  1252.                 /* append the extension and see if the file exists. */
  1253.                 tmp[namelen] = '\0';
  1254.                 strcat(tmp,script_suffixes[i]);
  1255.                 if(search_path (tmp, getenv("PATH"), prog)==1)
  1256.                      return 1;
  1257.             }
  1258.         }
  1259.     }
  1260.     /* should not be a script here */
  1261.     return 0;
  1262. }
  1263.  
  1264. char *
  1265. os2_shell(for_cmd)
  1266.   int for_cmd;
  1267. {
  1268.   char *make_shell,*comspec,*os2_shell;
  1269.  
  1270.   make_shell = getenv("MAKE_SHELL");
  1271.   comspec = getenv("COMSPEC");
  1272.   os2_shell = getenv("OS2_SHELL");
  1273.  
  1274.   if(make_shell != NULL && !for_cmd)
  1275.     return make_shell;
  1276.   else if(comspec != NULL)
  1277.     return comspec;
  1278.   else if(os2_shell != NULL)
  1279.     return os2_shell;
  1280.   else
  1281.     return default_shell;
  1282. }
  1283.  
  1284. int
  1285. is_cmd_exe(shell)
  1286.   char *shell;
  1287. {
  1288.   char basename[64];
  1289.   _splitpath(shell, NULL, NULL, basename, NULL);
  1290.   return (stricmp(basename,"4os2") == 0 || stricmp(basename,"cmd") == 0) ||
  1291.          (stricmp(basename,"4dos") == 0 || stricmp(basename,"command") == 0);
  1292. }
  1293.  
  1294. #else
  1295.  
  1296. static int
  1297. is_script(file)
  1298.      char *file;
  1299. {    return 0;
  1300. }
  1301.  
  1302. #endif
  1303.  
  1304. /* Replace the current process with one running the command in ARGV,
  1305.    with environment ENVP.  This function does not return.  */
  1306.  
  1307. #ifndef __EMX__
  1308. void
  1309. #else
  1310. int
  1311. #endif
  1312. exec_command (argv, envp)
  1313.      char **argv, **envp;
  1314. {
  1315.   char *shell, *path;
  1316.   PATH_VAR (program);
  1317.   register char **ep;
  1318. #ifdef __EMX__
  1319.   int pid = -1;
  1320. #endif
  1321.   shell = path = 0;
  1322.   for (ep = envp; *ep != 0; ++ep)
  1323.     {
  1324.       if (shell == 0 && !strncmp(*ep, "SHELL=", 6))
  1325.     shell = &(*ep)[6];
  1326.       else if (path == 0 && !strncmp(*ep, "PATH=", 5))
  1327.     path = &(*ep)[5];
  1328.       else if (path != 0 && shell != 0)
  1329.     break;
  1330.     }
  1331. #ifdef __EMX__
  1332.   if (shell == 0)
  1333.     shell = os2_shell(0);
  1334. #endif
  1335.  
  1336.   /* Be the user, permanently.  */
  1337.   child_access ();
  1338.  
  1339.   if (!search_path (argv[0], path, program))
  1340.     error ("%s: Command not found", argv[0]);
  1341.   else
  1342.     {
  1343. #ifndef __EMX__
  1344.       /* Run the program.  */
  1345.       execve (program, argv, envp);
  1346.       if (errno == ENOEXEC)
  1347. #else
  1348.       pid = spawnve(P_NOWAIT,program,
  1349.             (const char * const *)argv,
  1350.             (const char * const *)envp);
  1351.       if(pid == -1)
  1352. #endif      
  1353.     {
  1354.       PATH_VAR (shell_program);
  1355.       char *shell_path;
  1356.       if (shell == 0)
  1357. #ifdef __EMX__
  1358.         shell_path = default_shell;
  1359. #else
  1360.         shell_path = os2_shell(1);
  1361. #endif
  1362.       else
  1363.         {
  1364.           if (search_path (shell, path, shell_program))
  1365.         shell_path = shell_program;
  1366.           else
  1367.         {
  1368.           shell_path = 0;
  1369.           error ("%s: Shell program not found", shell);
  1370.         }
  1371.         }
  1372.  
  1373.       if (shell_path != 0)
  1374.         {
  1375.           char **new_argv;
  1376.           int argc, arg;
  1377.  
  1378.           argc = 1;
  1379.           while (argv[argc] != 0)
  1380.         ++argc;
  1381.  
  1382.           arg = 0;
  1383. #ifdef __EMX__
  1384.           new_argv = (char **) alloca ((1 + argc + 2) * sizeof (char *));
  1385.           new_argv[0] = shell_path;
  1386.           new_argv[++arg] = "/c";
  1387. #else
  1388.           new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
  1389.           new_argv[0] = shell_path;
  1390. #endif
  1391.           new_argv[++arg] = program;
  1392.           while (argc > 0)
  1393.         {
  1394.           new_argv[arg + argc] = argv[argc];
  1395.           --argc;
  1396.         }
  1397.  
  1398.           /* Run the program.  */
  1399. #ifndef __EMX__
  1400.           execve (shell_path, new_argv, envp);
  1401.           perror_with_name ("execve: ", shell_path);
  1402. #else
  1403.           pid = spawnve(P_NOWAIT,shell_path,
  1404.                 (const char * const *)new_argv,
  1405.                 (const char * const *)envp);
  1406.           if(pid == -1)
  1407.         perror_with_name ("spawnve: ", shell_path);
  1408. #endif      
  1409.         }
  1410.     }
  1411. #ifndef __EMX__
  1412.       else
  1413.     perror_with_name ("execve: ", program);
  1414. #endif
  1415.     }
  1416. #ifndef __EMX__
  1417.   _exit (127);
  1418. #else
  1419.   return pid;
  1420. #endif
  1421. }
  1422.  
  1423. /* Figure out the argument list necessary to run LINE as a command.
  1424.    Try to avoid using a shell.  This routine handles only ' quoting.
  1425.    Starting quotes may be escaped with a backslash.  If any of the
  1426.    characters in sh_chars[] is seen, or any of the builtin commands
  1427.    listed in sh_cmds[] is the first word of a line, the shell is used.
  1428.  
  1429.    If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
  1430.    If *RESTP is NULL, newlines will be ignored.
  1431.  
  1432.    SHELL is the shell to use, or nil to use the default shell.
  1433.    IFS is the value of $IFS, or nil (meaning the default).  */
  1434.  
  1435. static char **
  1436. construct_command_argv_internal (line, restp, shell, ifs)
  1437.      char *line, **restp;
  1438.      char *shell, *ifs;
  1439. {
  1440. #ifndef __EMX__
  1441.   static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
  1442. #else
  1443.   static char sh_chars[] = "&|<>^()";
  1444.   int is_cmd = 1;
  1445. #endif
  1446.   register int i;
  1447.   register char *p;
  1448.   register char *ap;
  1449.   char *end;
  1450.   int instring, word_has_equals, seen_nonequals;
  1451.   char **new_argv = 0;
  1452.  
  1453.   if (restp != NULL)
  1454.     *restp = NULL;
  1455.  
  1456.   /* Make sure not to bother processing an empty line.  */
  1457.   while (isblank (*line))
  1458.     ++line;
  1459.   if (*line == '\0')
  1460.     return 0;
  1461.  
  1462.   /* See if it is safe to parse commands internally.  */
  1463.   if (shell == 0)
  1464. #ifndef __EMX__
  1465.     shell = default_shell;
  1466.   else if (strcmp (shell, default_shell))
  1467.     goto slow;
  1468. #else
  1469.     shell = os2_shell(0);
  1470.   else
  1471.     if (!(is_cmd = is_cmd_exe(shell)))
  1472.     goto slow;
  1473. #endif
  1474.  
  1475.   if (ifs != 0)
  1476.     for (ap = ifs; *ap != '\0'; ++ap)
  1477.       if (*ap != ' ' && *ap != '\t' && *ap != '\n')
  1478.     goto slow;
  1479.  
  1480.   i = strlen (line) + 1;
  1481.  
  1482.   /* More than 1 arg per character is impossible.  */
  1483.   new_argv = (char **) xmalloc (i * sizeof (char *));
  1484.  
  1485.   /* All the args can fit in a buffer as big as LINE is.   */
  1486.   ap = new_argv[0] = (char *) xmalloc (i);
  1487.   end = ap + i;
  1488.  
  1489.   /* I is how many complete arguments have been found.  */
  1490.   i = 0;
  1491.   instring = word_has_equals = seen_nonequals = 0;
  1492.   for (p = line; *p != '\0'; ++p)
  1493.     {
  1494.       if (ap > end)
  1495.     abort ();
  1496.  
  1497.       if (instring)
  1498.     {
  1499.       /* Inside a string, just copy any char except a closing quote
  1500.          or a backslash-newline combination.  */
  1501.       if (*p == instring)
  1502.         instring = 0;
  1503.       else if (*p == '\\' && p[1] == '\n')
  1504.         goto swallow_escaped_newline;
  1505. #ifdef __EMX__
  1506.       else if (*p == '\\') /* except if guarded by \ */
  1507.         *ap++ = *++p;
  1508. #endif
  1509.       else if (*p == '\n' && restp != NULL)
  1510.         {
  1511.           /* End of the command line.  */
  1512.           *restp = p;
  1513.           goto end_of_line;
  1514.         }
  1515.       else
  1516.         *ap++ = *p;
  1517.     }
  1518.       else if (index (sh_chars, *p) != 0)
  1519.     /* Not inside a string, but it's a special char.  */
  1520.     goto slow;
  1521.       else
  1522.     /* Not a special char.  */
  1523.     switch (*p)
  1524.       {
  1525.       case '=':
  1526.         /* Equals is a special character in leading words before the
  1527.            first word with no equals sign in it.  This is not the case
  1528.            with sh -k, but we never get here when using nonstandard
  1529.            shell flags.  */
  1530.         if (! seen_nonequals)
  1531.           goto slow;
  1532.         word_has_equals = 1;
  1533.         *ap++ = '=';
  1534.         break;
  1535.  
  1536.       case '\\':
  1537.         /* Backslash-newline combinations are eaten.  */
  1538.         if (p[1] == '\n')
  1539.           {
  1540.           swallow_escaped_newline:
  1541.  
  1542.         /* Eat the backslash, the newline, and following whitespace,
  1543.            replacing it all with a single space.  */
  1544.         p += 2;
  1545.  
  1546.         /* If there is a tab after a backslash-newline,
  1547.            remove it from the source line which will be echoed,
  1548.            since it was most likely used to line
  1549.            up the continued line with the previous one.  */
  1550.         if (*p == '\t')
  1551.           strcpy (p, p + 1);
  1552.  
  1553.         if (instring)
  1554.           *ap++ = *p;
  1555.         else
  1556.           {
  1557.             if (ap != new_argv[i])
  1558.               /* Treat this as a space, ending the arg.
  1559.              But if it's at the beginning of the arg, it should
  1560.              just get eaten, rather than becoming an empty arg. */
  1561.               goto end_of_arg;
  1562.             else
  1563.               p = next_token (p) - 1;
  1564.           }
  1565.           }
  1566.         else if (p[1] != '\0') {
  1567. #ifdef __EMX__
  1568.           /* for OS/2, let's keep single \ before characters and numbers
  1569.          because \ is commonly used as path name separator */
  1570.           if (isalnum(p[1]))
  1571.         *ap++ = *p;
  1572. #endif
  1573.           /* Copy and skip the following char.  */
  1574.           *ap++ = *++p;
  1575.         }
  1576.         break;
  1577.  
  1578. #ifdef __EMX__
  1579.       case '"':
  1580. #endif
  1581.       case '\'':
  1582.         instring = *p;
  1583.         break;
  1584.  
  1585.       case '\n':
  1586.         if (restp != NULL)
  1587.           {
  1588.         /* End of the command line.  */
  1589.         *restp = p;
  1590.         goto end_of_line;
  1591.           }
  1592.         else
  1593.           /* Newlines are not special.  */
  1594.           *ap++ = '\n';
  1595.         break;
  1596.  
  1597.       case ' ':
  1598.       case '\t':
  1599.       end_of_arg:
  1600.         /* We have the end of an argument.
  1601.            Terminate the text of the argument.  */
  1602.         *ap++ = '\0';
  1603.         new_argv[++i] = ap;
  1604.  
  1605.         /* Update SEEN_NONEQUALS, which tells us if every word
  1606.            heretofore has contained an `='.  */
  1607.         seen_nonequals |= ! word_has_equals;
  1608.         if (word_has_equals && ! seen_nonequals)
  1609.           /* An `=' in a word before the first
  1610.          word without one is magical.  */
  1611.           goto slow;
  1612.         word_has_equals = 0; /* Prepare for the next word.  */
  1613.  
  1614.         /* If this argument is the command name,
  1615.            see if it is a built-in shell command.
  1616.            If so, have the shell handle it.  */
  1617.         if (i == 1) {
  1618.             if(is_shell_command(new_argv[0]))
  1619.           goto slow;
  1620. #ifdef __EMX__
  1621.             if (is_script(new_argv[0]))
  1622.             goto slow;
  1623. #endif                
  1624.           }
  1625.         /* Ignore multiple whitespace chars.  */
  1626.         p = next_token (p);
  1627.         /* Next iteration should examine the first nonwhite char.  */
  1628.         --p;
  1629.         break;
  1630.  
  1631.       default:
  1632.         *ap++ = *p;
  1633.         break;
  1634.       }
  1635.     }
  1636.  end_of_line:
  1637.  
  1638.   if (instring)
  1639.     /* Let the shell deal with an unterminated quote.  */
  1640.     goto slow;
  1641.  
  1642.   /* Terminate the last argument and the argument list.  */
  1643.  
  1644.   *ap = '\0';
  1645.   if (new_argv[i][0] != '\0')
  1646.     ++i;
  1647.   new_argv[i] = 0;
  1648.  
  1649.   if (i == 1)
  1650.     {
  1651.       if (is_shell_command(new_argv[0]))
  1652.     goto slow;
  1653. #ifndef __EMX__
  1654.       if (is_script(new_argv[0]))
  1655.       goto slow;
  1656. #endif
  1657.     }
  1658.  
  1659.   if (new_argv[0] == 0)
  1660.     /* Line was empty.  */
  1661.     return 0;
  1662.   else
  1663.     return new_argv;
  1664.  
  1665.  slow:;
  1666.   /* We must use the shell.  */
  1667.  
  1668.   if (new_argv != 0)
  1669.     {
  1670.       /* Free the old argument list we were working on.  */
  1671.       free (new_argv[0]);
  1672.       free (new_argv);
  1673.     }
  1674.  
  1675.   {
  1676.     /* SHELL may be a multi-word command.  Construct a command line
  1677.        "SHELL -c LINE", with all special chars in LINE escaped.
  1678.        Then recurse, expanding this command line to get the final
  1679.        argument list.  */
  1680.     
  1681.     unsigned int shell_len = strlen (shell);
  1682. #ifndef __EMX__
  1683.     static char minus_c[] = " -c ";
  1684. #define MINUS_C_SIZE sizeof(minus_c)
  1685. #else
  1686.     char *minus_c = " /c ";
  1687. #define MINUS_C_SIZE (strlen(minus_c)+1)
  1688. #endif
  1689.     unsigned int line_len = strlen (line);
  1690.     char *new_line;
  1691. #ifdef __EMX__
  1692.     if(!is_cmd)
  1693.       minus_c = " -c ";
  1694. #endif    
  1695.     new_line = (char *) alloca (shell_len + (MINUS_C_SIZE - 1)
  1696.                       + (line_len * 2) + 1);
  1697.     ap = new_line;
  1698.     bcopy (shell, ap, shell_len);
  1699.     ap += shell_len;
  1700.     bcopy (minus_c, ap, MINUS_C_SIZE - 1);
  1701.     ap += MINUS_C_SIZE - 1;
  1702.     for (p = line; *p != '\0'; ++p)
  1703.       {
  1704.     if (restp != NULL && *p == '\n')
  1705.       {
  1706.         *restp = p;
  1707.         break;
  1708.       }
  1709.     else if (*p == '\\' && p[1] == '\n')
  1710.       {
  1711.         /* Eat the backslash, the newline, and following whitespace,
  1712.            replacing it all with a single space.  */
  1713.         p += 2;
  1714.  
  1715.         /* If there are tabs after a backslash-newline,
  1716.            remove them from the source line which will be echoed,
  1717.            since they were most likely used to line
  1718.            up the continued line with the previous one.  */
  1719.         while (*p == '\t')
  1720.           strcpy (p, p + 1);
  1721.  
  1722.         p = next_token (p);
  1723.         --p;
  1724. #ifdef __EMX__
  1725.         if (!is_cmd)
  1726. #endif
  1727.         *ap++ = '\\';
  1728.         *ap++ = ' ';
  1729.         continue;
  1730.       }
  1731.  
  1732.     if (*p == '\\' ||
  1733.         *p == '\'' ||
  1734. #ifdef __EMX__
  1735.         *p == '"' ||
  1736. #endif
  1737.         isspace (*p) ||
  1738.         index (sh_chars, *p) != 0)
  1739. #ifdef __EMX__
  1740.       if(!is_cmd || index(sh_chars,*p) != 0)
  1741. #endif
  1742.       *ap++ = '\\';
  1743.     *ap++ = *p;
  1744.       }
  1745.     *ap = '\0';
  1746.     
  1747.     new_argv = construct_command_argv_internal (new_line, (char **) NULL,
  1748.                         (char *) 0, (char *) 0);
  1749.   }
  1750.  
  1751.   return new_argv;
  1752. }
  1753.  
  1754. /* Figure out the argument list necessary to run LINE as a command.
  1755.    Try to avoid using a shell.  This routine handles only ' quoting.
  1756.    Starting quotes may be escaped with a backslash.  If any of the
  1757.    characters in sh_chars[] is seen, or any of the builtin commands
  1758.    listed in sh_cmds[] is the first word of a line, the shell is used.
  1759.  
  1760.    If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
  1761.    If *RESTP is NULL, newlines will be ignored.
  1762.  
  1763.    FILE is the target whose commands these are.  It is used for
  1764.    variable expansion for $(SHELL) and $(IFS).  */
  1765.  
  1766. char **
  1767. construct_command_argv (line, restp, file)
  1768.      char *line, **restp;
  1769.      struct file *file;
  1770. {
  1771.   char *shell, *ifs;
  1772.   char **argv;
  1773.  
  1774.   {
  1775.     /* Turn off --warn-undefined-variables while we expand SHELL and IFS.  */
  1776.     int save = warn_undefined_variables_flag;
  1777.     warn_undefined_variables_flag = 0;
  1778.  
  1779.     shell = allocated_variable_expand_for_file ("$(SHELL)", file);
  1780.     ifs = allocated_variable_expand_for_file ("$(IFS)", file);
  1781.  
  1782.     warn_undefined_variables_flag = save;
  1783.   }
  1784.  
  1785.   argv = construct_command_argv_internal (line, restp, shell, ifs);
  1786.  
  1787.   free (shell);
  1788.   free (ifs);
  1789.  
  1790.   return argv;
  1791. }
  1792.  
  1793. #ifndef    HAVE_DUP2
  1794. int
  1795. dup2 (old, new)
  1796.      int old, new;
  1797. {
  1798.   int fd;
  1799.  
  1800.   (void) close (new);
  1801.   fd = dup (old);
  1802.   if (fd != new)
  1803.     {
  1804.       (void) close (fd);
  1805.       errno = EMFILE;
  1806.       return -1;
  1807.     }
  1808.  
  1809.   return fd;
  1810. }
  1811. #endif
  1812.